package com.xbongbong.paas.service.team.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.service.ClueRuleService;
import com.xbongbong.paas.service.TransferBackRuleScriptService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.TeamStrategy;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailEditLabelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailUpdateDTO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditCoPerVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditLabelVO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.teammembers.enums.CoUserPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormCoUserDefaultPermissionEnum;
import com.xbongbong.pro.listbatch.pojo.TeamBatchPojo;
import com.xbongbong.pro.team.TeamAfterFormatDTO;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.ClueUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.enums.ClueRuleEnum;
import com.xbongbong.saas.enums.UserTeamOperateTagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.service.impl.ListBatchServiceImpl;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author shen.yang
 * @version v1.0
 * @Description 销售线索团队策略类
 * @date 2022/1/19 15:10
 * @since v1.0
 */
@Service
public class ClueTeamStrategy extends AbstractTeamStrategy implements TeamStrategy {
    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private ClueRuleService clueRuleService;
    @Resource
    private UserModel userModel;
    @Resource
    private ListBatchServiceImpl listBatchService;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private TransferBackRuleScriptService transferBackRuleScriptService;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.CLUE.getCode());
    }

    @Override
    public TeamAfterVerifyDTO verify(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        return super.verifyTeam(teamVerifyDTO);
    }

    @Override
    public TeamAfterVerifyDTO specialVerify(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        Integer operateTag = teamAfterVerifyDTO.getOperateTag();
        List<TeamBatchPojo> teamBatchPojos = new ArrayList<>();
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            //移交的公海池校验
            checkHandleOverPublicRule(teamAfterVerifyDTO);
        }else {
            //公海池校验
            teamBatchPojos = checkPublicRule(corpid, teamAfterVerifyDTO.getDataId(), teamAfterVerifyDTO.getBusinessType(), teamAfterVerifyDTO.getAddMainUserMap(),
                    teamAfterVerifyDTO.getOperateTag(), teamAfterVerifyDTO.getTeamBatchPojos(), teamAfterVerifyDTO.getFromDetail(), teamAfterVerifyDTO.getIsNew());
        }
        if(Objects.isNull(teamAfterVerifyDTO.getTeamBatchPojos())){
            teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
        }else{
            teamAfterVerifyDTO.getTeamBatchPojos().addAll(teamBatchPojos);
        }

        return teamAfterVerifyDTO;
    }

    /**
     * 校验移交的公海池规则
     *
     * @param teamAfterVerifyDTO 经过上层校验得到的一个实体
     */
    private void checkHandleOverPublicRule(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException{
        List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
        String corpid = teamAfterVerifyDTO.getCorpid();
        List<Long> dataIdList = teamAfterVerifyDTO.getDataId();
        List<Long> originalIdList = (List<Long>)CloneUtil.deepClone(dataIdList);
        String changeUserId = teamAfterVerifyDTO.getChangeUserId();
        List<Long> existTeamBatchDataIdList = new ArrayList<>();
        Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
        Map<String, Set<String>> delMainUserMap = Objects.nonNull(teamAfterVerifyDTO.getDelMainUserMap()) ?  teamAfterVerifyDTO.getDelMainUserMap() : new HashMap<>();
        if (Objects.nonNull(addMainUserMap) && Objects.equals(UserTeamOperateTagEnum.GET_CUSTOMER.getOperateTag(), teamAfterVerifyDTO.getOperateTag())) {
            Set<String> userIdSet = addMainUserMap.values().stream().findFirst().get();
            changeUserId = new ArrayList<>(userIdSet).get(BasicConstant.ZERO);
        }
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            existTeamBatchDataIdList = teamBatchPojos.stream().map(TeamBatchPojo::getDataId).collect(Collectors.toList());
        }
        UserEntity userEntity = userModel.getByKey(changeUserId, corpid);
        if (Objects.isNull(userEntity)) {
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
            teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_271036.getCode());
            teamBatchPojo.setFailMsg(I18nMessageUtil.getMessage(TeamMembersConstant.TEAM_MEMBER_ERROR));
            teamBatchPojo.setFailMsgReason(I18nMessageUtil.getMessage(TeamMembersConstant.USER_NOT_EXIST));
            teamBatchPojos.add(teamBatchPojo);
            return;
        }
        Map<Long, PaasFormDataEntityExt> entityExtMap = new HashMap<>(dataIdList.size());
        // 公海池规则的判断处理
        Map<Integer, List<String>> clueRuleErrorMap = new HashMap<>(BasicConstant.ONE);
        Map<Long, String> clueNameMap = getClueNameMap(dataIdList, corpid, entityExtMap);
        clueRuleErrorMap = listBatchService.canGainClue(corpid, dataIdList, userEntity, entityExtMap);
        clueRuleError(clueRuleErrorMap, teamBatchPojos, originalIdList, clueNameMap, existTeamBatchDataIdList, addMainUserMap, delMainUserMap);
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            return;
        }
        if (!clueRuleErrorMap.isEmpty()) {
            (CollectionsUtil.isNotEmpty(originalIdList) ? originalIdList : new ArrayList<>()).removeAll(CollectionsUtil.isNotEmpty(dataIdList) ? dataIdList : new ArrayList<>());
            for (Long dataId : originalIdList) {
                //这些都是异常数据
                if (existTeamBatchDataIdList.contains(dataId)) {
                    continue;
                }
                String clueName = clueNameMap.get(dataId);
                TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271026.getCode(), UserTeamErrorCodeEnum.API_ERROR_271026.getMsg(),
                        clueName, UserTeamOperateTagEnum.HANDOVER.getName());
                teamBatchPojos.add(teamBatchPojo);
            }
        }
    }

    private Map<Long, String> getClueNameMap(List<Long> handoverIdSet, String corpid, Map<Long, PaasFormDataEntityExt> entityExtMap) throws XbbException{
        Map<Long,String> clueNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (handoverIdSet.isEmpty()){
            return clueNameMap;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),handoverIdSet));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CLUE.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, handoverIdSet.size());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CLUE.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        for (PaasFormDataEntityExt entity : esEntities.getContent()){
            clueNameMap.put(entity.getDataId(),entity.getData().getString(ClueEnum.COMPANY_NAME.getAttr()));
            entityExtMap.put(entity.getDataId(), entity);
        }
        return clueNameMap;
    }

    /**
     * 最大公海池规则和捞取频率规则的报错信息处理
     *
     * @param clueRuleErrorMap
     * @param teamBatchPojos
     * @param dataIdList
     * @param clueNameMap
     * @param existTeamBatchDataIdList
     * @throws
     */
    private void clueRuleError(Map<Integer, List<String>> clueRuleErrorMap, List<TeamBatchPojo> teamBatchPojos, List<Long> dataIdList,
                               Map<Long, String> clueNameMap, List<Long> existTeamBatchDataIdList, Map<String, Set<String>> addMainUserMap,
                               Map<String, Set<String>> delMainUserMap) {
        if (clueRuleErrorMap.isEmpty()) {
            return;
        }
        for (Map.Entry<Integer, List<String>> entry : clueRuleErrorMap.entrySet()) {
            if (Objects.equals(entry.getKey(), ClueRuleEnum.MAX_CLUE_NUM_RULE.getCode())) {
                for (Long dataId : dataIdList) {
                    if (existTeamBatchDataIdList.contains(dataId)) {
                        continue;
                    }
                    String clueName = clueNameMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271029.getCode(), UserTeamErrorCodeEnum.API_ERROR_271029.getMsg(),
                            clueName, UserTeamOperateTagEnum.HANDOVER.getName(), dataId);
                    teamBatchPojos.add(teamBatchPojo);
                    addMainUserMap.remove(String.valueOf(dataId));
                    delMainUserMap.remove(String.valueOf(dataId));
                }
                break;
            } else if (Objects.equals(entry.getKey(), ClueRuleEnum.GAIN_RATE_RULE.getCode())) {
                for (Long dataId : dataIdList) {
                    if (existTeamBatchDataIdList.contains(dataId)) {
                        continue;
                    }
                    String clueName = clueNameMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271030.getCode(), UserTeamErrorCodeEnum.API_ERROR_271030.getMsg(),
                            clueName, UserTeamOperateTagEnum.HANDOVER.getName(), dataId);
                    teamBatchPojos.add(teamBatchPojo);
                    addMainUserMap.remove(String.valueOf(dataId));
                    delMainUserMap.remove(String.valueOf(dataId));
                }
                break;
            }
        }
        /*for (Map.Entry<Integer, List<String>> entry : clueRuleErrorMap.entrySet()) {
            if (Objects.equals(entry.getKey(), ClueRuleEnum.MAX_CLUE_NUM_RULE.getCode())) {
                TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                teamBatchPojo.setFailMsgReason(I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_CLUE_RULE));
                mergeFailMsg(teamBatchPojo, operateStr, teamBatchVO);
                teamBatchPojos.add(teamBatchPojo);
                break;
            } else if (Objects.equals(entry.getKey(), ClueRuleEnum.GAIN_RATE_RULE.getCode())) {
                TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                teamBatchPojo.setFailMsgReason(I18nMessageUtil.getMessage(I18nMessageUtil.getMessage(ListBatchConstant.CLUE_NUM_EXCEEDS_GAIN_CLUE_RULE)));
                mergeFailMsg(teamBatchPojo, operateStr, teamBatchVO);
                teamBatchPojos.add(teamBatchPojo);
                break;
            }
        }*/
    }

    @Override
    public void save(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        TeamAfterFormatDTO teamAfterFormatDTO = formatTeam(teamAfterVerifyDTO);

        LinkedHashMap<String, Integer> esWait = judgeTeamEsWait(teamAfterFormatDTO);

        for (Iterator<Map.Entry<String, Integer>> iterator = esWait.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Integer> entry = iterator.next();
            boolean hasNext = iterator.hasNext();
            switch (entry.getKey()) {
                case TeamMembersConstant.ADD_USER:
                    List<UserTeamEntity> addUserTeamList = teamAfterFormatDTO.getAddUserTeamList();
                    if (CollectionsUtil.isNotEmpty(addUserTeamList)) {
                        List<ClueUserEntity> clueUserEntityList = new ArrayList<>();
                        try {
                            BeanUtil.copyPropertiesList(addUserTeamList, clueUserEntityList, ClueUserEntity.class, false);
                        } catch (Exception e) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                        }

                        if (hasNext) {
                            clueUserModel.insertBatch(clueUserEntityList, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            clueUserModel.insertBatch(clueUserEntityList, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.DEL_USER:
                    List<UserTeamEntity> delUserTeamList = teamAfterFormatDTO.getDelUserTeamList();
                    if (CollectionsUtil.isNotEmpty(delUserTeamList)) {
                        List<Long> idIn = delUserTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());

                        if (hasNext) {
                            clueUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            clueUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.TO_MAIN_USER:
                    List<UserTeamEntity> updateUserToMainTeamList = teamAfterFormatDTO.getUpdateUserToMainTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToMainTeamList)) {
                        List<Long> idIn = updateUserToMainTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            clueUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            clueUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.TO_CO_USER:
                    List<UserTeamEntity> updateUserToCoTeamList = teamAfterFormatDTO.getUpdateUserToCoTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToCoTeamList)) {
                        List<Long> idIn = updateUserToCoTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            clueUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            clueUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.UPDATE_USER:
                    List<UserTeamEntity> updateUserTeamMainList = teamAfterFormatDTO.getUpdateUserTeamMainList();
                    if (CollectionsUtil.isNotEmpty(updateUserTeamMainList)) {
                        //这边需要更新团队成员的teamUserId，这个字段是不需要存数据库的，但是es还是需要更新一下更新时间
                        List<Long> idIn = updateUserTeamMainList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            clueUserModel.batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            clueUserModel.batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                default:
            }

        }
    }

    @Override
    public void afterSave(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        List<Long> dataId = teamAfterVerifyDTO.getDataId();
        //更新时间
        List<UpdateDataEntity> updateDataEntityArrayList = new ArrayList<>();
        //只有不是删除负责人的场景下才会更新分配时间，注意移交的时候会有删除负责人的动作，所以这个移交需要考虑进来,有问题找梦娜产品
        for (int i = 0; i < dataId.size(); i++) {
            UpdateDataEntity updateData = new UpdateDataEntity();
            Set<String> addUserSet = teamAfterVerifyDTO.getAddMainUserMap().get(String.valueOf(dataId.get(i)));
            Set<String> updateToMainUserSet = teamAfterVerifyDTO.getUpdateToMainUserMap().get(String.valueOf(dataId.get(i)));
            if (CollectionsUtil.isNotEmpty(addUserSet) || CollectionsUtil.isNotEmpty(updateToMainUserSet) || Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamAfterVerifyDTO.getOperateTag())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(ClueEnum.DISTRIBUTION_DATE.getAttr(), DateTimeUtil.getInt());
                //此方法会更新updatetime为当前时间
                updateData = ExplainUtil.getUpdateData(dataId.get(i), jsonObject, corpid);
            }else {
                updateData.setId(dataId.get(i));
                updateData.setCorpid(corpid);
            }
            //最新的操作一定要保证更新时间最新
            updateData.setUpdateTime(DateUtil.getNow()+1);
            updateDataEntityArrayList.add(updateData);
        }
        clueModel.updateBatch(updateDataEntityArrayList, corpid, WriteRequest.RefreshPolicy.NONE);


        //添加团队成员要更新redis中的捞取频次(随老逻辑只有在负责人插入的时候更新)
        Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
        Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
        //先过滤value为null的，否则 v.getValue().stream() 空指针;后续增加逻辑，只有非捞取、分配、移交，才会走下面方法，区分的原因是因为这几个入口有批量逻辑 issue#50574,把逻辑放到他们service层处理
        if (!Objects.equals(UserTeamOperateTagEnum.GET_CUSTOMER.getOperateTag(), teamAfterVerifyDTO.getOperateTag())
                && !Objects.equals(UserTeamOperateTagEnum.DISTRIBUTION.getOperateTag(), teamAfterVerifyDTO.getOperateTag())
                && !Objects.equals(true, teamAfterVerifyDTO.getIsNew())) {
            List<String> idList = addMainUserMap.entrySet().stream()
                    .filter(v -> Objects.nonNull(v.getValue()))
                    .flatMap(v -> v.getValue().stream())
                    .distinct().collect(Collectors.toList());
            List<UserEntity> users = userModel.findEntitysByUserIds(idList, corpid);
            for (Long data: dataId) {
                Set<String> addMainUsers = addMainUserMap.getOrDefault(String.valueOf(data), new HashSet<>());
                List<UserEntity> collect = users.stream().filter(v -> addMainUsers.contains(v.getUserId())).collect(Collectors.toList());
                for (UserEntity userEntity : collect) {
                    clueRuleService.updateGainRateToRedis(corpid, userEntity);
                }
            }
        }

        if (Objects.equals(teamAfterVerifyDTO.getOperateTag(), UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            if (Objects.nonNull(delMainUserMap)) {
                List<Long> clueIds = Optional.of(addMainUserMap.keySet()).get().stream().map(Long::valueOf).collect(Collectors.toList());
                boolean cluePublicPoolSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
                if (cluePublicPoolSeniorModel){
                    transferBackRuleScriptService.deletePublicSeniorTag(corpid,clueIds,XbbRefTypeEnum.CLUE.getCode(),teamAfterVerifyDTO.getFormId());
                }else {
                    clueRuleService.deletePublicTag(corpid, clueIds);
                }
            }
        }
    }

    @Override
    public void log(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        super.log(teamAfterVerifyDTO);
    }

    @Override
    public TeamDetailEditCoPerVO editCoPermission(TeamDetailUpdateDTO teamDetailUpdateDTO) throws XbbException {
        TeamDetailEditCoPerVO teamDetailEditCoPerVO = new TeamDetailEditCoPerVO();
        Long dataId = teamDetailUpdateDTO.getDataId();
        String corpid = teamDetailUpdateDTO.getCorpid();
        Long id = teamDetailUpdateDTO.getId();
        //编辑协同人权限
        Integer formPermission = teamDetailUpdateDTO.getFormPermission();
        ClueUserEntity shouldUpdateEntity = clueUserModel.getByKey(id, corpid);
        if(Objects.nonNull(shouldUpdateEntity)){
            Integer dbFormPermission = shouldUpdateEntity.getFormPermission();
            if (Objects.isNull(dbFormPermission)) {
                dbFormPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(teamDetailUpdateDTO.getBusinessType());
            }
            if (!Objects.equals(formPermission, dbFormPermission)) {
                shouldUpdateEntity.setFormPermission(formPermission);
                clueUserModel.updateEditFormPer(shouldUpdateEntity);
                clueModel.updateTime(dataId,corpid);
                String content = "";
                if (Objects.equals(formPermission, CoUserPermissionEnum.EDIT.getPermissionValue())) {
                    content = I18nMessageUtil.getMessage(TeamMembersConstant.EDIT);
                }else {
                    content = I18nMessageUtil.getMessage(TeamMembersConstant.NO_EDIT);
                }
                ClueEntityExt clueEntityExt = clueModel.getByKey(dataId, corpid);
                saveUpdateCoPerLogger(teamDetailUpdateDTO.getLoginUser(), teamDetailUpdateDTO.getFormId(), shouldUpdateEntity.getUserId(),
                        corpid, teamDetailUpdateDTO.getBusinessType(), clueEntityExt,  content, teamDetailUpdateDTO.getHttpHeader());
            }
        }
        return teamDetailEditCoPerVO;
    }

    @Override
    public TeamDetailEditLabelVO editLabel(TeamDetailEditLabelDTO teamDetailEditLabelDTO) throws XbbException {
        TeamDetailEditLabelVO teamDetailEditLabelVO = new TeamDetailEditLabelVO();
        String corpid = teamDetailEditLabelDTO.getCorpid();
        Long id = teamDetailEditLabelDTO.getId();
        Long dataId = teamDetailEditLabelDTO.getDataId();
        JSONArray labels = teamDetailEditLabelDTO.getLabels();
        ClueUserEntity clueUserEntity = clueUserModel.getByKey(id, corpid);
        JSONArray dbLabels = clueUserEntity.getLabels();
        List<Long> lbIdFormList = new ArrayList<>();
        List<Long> lbIdSysList = new ArrayList<>();
        List<Long> dbLbIdFormList = new ArrayList<>();
        List<Long> dbLbIdSysList = new ArrayList<>();
        boolean addTag = userTeamHelp.getAddLogTag(labels, dbLabels, lbIdFormList, lbIdSysList, dbLbIdFormList, dbLbIdSysList);
        if (addTag) {
            clueUserEntity.setLabels(labels);
            clueUserModel.editLabel(clueUserEntity);
            //更新主业务的更新时间
            clueModel.updateTime(dataId,corpid);
            ClueEntityExt clueEntityExt = clueModel.getByKey(dataId, corpid);
            //记录日志信息
            saveUpdateLabelLogger(teamDetailEditLabelDTO.getLoginUser(), teamDetailEditLabelDTO.getFormId(), clueUserEntity.getUserId(), corpid,
                    teamDetailEditLabelDTO.getBusinessType(), clueEntityExt, clueUserEntity.getIsMain(), teamDetailEditLabelDTO.getHttpHeader(),
                    lbIdFormList, lbIdSysList, dbLbIdFormList, dbLbIdSysList, clueUserEntity.getUpdateTime());
        }
        return teamDetailEditLabelVO;
    }
}
